import os
import random
import datetime

from django.http import HttpResponse
from django.utils import simplejson as json
from django.template import RequestContext
from django.shortcuts import render_to_response

import cwd.settings as settings
from cwd.gridpoints.models import Gridpoint
from cwd.lib.graphs import BarGraph, MonthlyPercentile, PrecipBarGraph
from cwd.lib.utils import TextOutput

# Create your views here.

def main_view(request):
    context = {
    }
    return render_to_response('main.html', context, context_instance=RequestContext(request))

def bargraph_panel(request):
    return HttpResponse(
	"""
	<img src="%(prefix)sproducts/bargraph.png?month=%(month)s&lat=%(lat)s&lon=%(lon)s&span=%(span)s&frztype=%(frztype)s&runavg=%(runavg)s&units=%(units)s" />
        <pre>%(text_data)s</pre>
	""" % {
            "prefix": settings.URL_PREFIX,
            "month": request.GET.get("month",1),
            "lat": request.GET.get("lat"),
            "lon": request.GET.get("lon"),
            "span": request.GET.get("span",1),
            "runavg": request.GET.get("runavg",0),
            "frztype": request.GET.get("frztype",0),
            "units": request.GET.get('units','m').lower(),
            "text_data": frz_bargraph_png(request,format="text").content,
	}
    )

def frz_bargraph_png(request, format="png"):
    month = int(request.GET.get('month',1))
    span = int(request.GET.get('span',1))
    runavg = int(request.GET.get('runavg',0))
    frztype = int(request.GET.get('frztype',0))
    try:
        lat = float(request.GET.get('lat'))
    except ValueError:
        lat = None
    try:
        lon = abs(float(request.GET.get('lon')))
    except ValueError:
        lon = None
    units = request.GET.get('units','m').lower()
    if not units in ('ft','m'):
        units = 'm'
    if not 0 < month <= 12:
	return HttpResponse("Invalid month")
    if lat is None or lon is None:
	return HttpResponse("Lat/Lon required.")
    if not 0 <= frztype <= 3:
	return HttpResponse("Invalid freeze level")

    if format == "text":
        response = HttpResponse(content_type='text/plain')
        text_output = TextOutput(print_to=response,delim=",")
        bargraph = BarGraph(lat,lon,month,span,frztype,runavg,units)
        bargraph.write_to(text_output, format="text")
    else:
        # Create a response object
        response = HttpResponse(content_type='image/png')
        # Generate grapher
        bargraph = BarGraph(lat,lon,month,span,frztype,runavg,units)
        # Write graph to response
        bargraph.write_to(response)

    return response

def monthly_perc_map(request):
    context = {}
    return render_to_response('gridpoint_map4.html', context, context_instance=RequestContext(request))

def frz_monthly_percentile(request, format="png"):
    try:
        lat = float(request.GET.get('lat'))
    except ValueError:
        lat = None
    try:
        lon = abs(float(request.GET.get('lon')))
    except ValueError:
        lon = None
    if lat is None or lon is None:
	return HttpResponse("Lat/Lon required.")
    frztype = float(request.GET.get('frztype',0))
    units = request.GET.get('units','m').lower()
    if not units in ('ft','m'):
        units = 'm'

    if format == "text":
        response = HttpResponse(content_type='text/plain')
        text_output = TextOutput(print_to=response,delim=",")
        graph = MonthlyPercentile(lat,lon,frztype,units)
        graph.write_to(text_output,format="text")
    else:
        response = HttpResponse(content_type='image/png')
        graph = MonthlyPercentile(lat,lon,frztype,units)
        graph.write_to(response)
    return response

def monthly_perc_panel(request):
    return HttpResponse(
	"""
        <img src="%(prefix)sproducts/monthly_perc.png?frztype=%(frztype)s&lat=%(lat)s&lon=%(lon)s&units=%(units)s" />
        <pre>%(text_data)s</pre>
	""" % {
            "prefix": settings.URL_PREFIX,
            "frztype": request.GET.get("frztype",0),
            "units": request.GET.get('units','m').lower(),
            "lat": request.GET.get("lat"),
            "lon": request.GET.get("lon"),
            "text_data": frz_monthly_percentile(request,format="text").content,
	}
    )


def precip_bargraph_panel(request):
    return HttpResponse(
	"""
	<img src="%(prefix)sproducts/precip_bargraph.png?month=%(month)s&lat=%(lat)s&lon=%(lon)s&span=%(span)s&level=%(level)s&runavg=%(runavg)s" />
        <pre>%(text_data)s</pre>
	""" % {
            "prefix": settings.URL_PREFIX,
            "month": request.GET.get("month",1),
            "lat": request.GET.get("lat"),
            "lon": request.GET.get("lon"),
            "span": request.GET.get("span",1),
            "runavg": request.GET.get("runavg",0),
            "level": request.GET.get("level",0),
            "text_data": precip_bargraph_png(request,format="text").content,
	}
    )

def precip_bargraph_png(request, format="png"):
    month = int(request.GET.get('month',1))
    span = int(request.GET.get('span',1))
    runavg = int(request.GET.get('runavg',0))
    level = int(request.GET.get('level',0))
    try:
        lat = float(request.GET.get('lat'))
    except ValueError:
        lat = None
    try:
        lon = abs(float(request.GET.get('lon')))
    except ValueError:
        lon = None
    if not 0 < month <= 12:
	return HttpResponse("Invalid month")
    if lat is None or lon is None:
	return HttpResponse("Lat/Lon required.")
    if not 0 <= level <= 20:
	return HttpResponse("Invalid elevation level")

    if format == "text":
        response = HttpResponse(content_type='text/plain')
        text_output = TextOutput(print_to=response,delim=",")
        bargraph = PrecipBarGraph(lat,lon,month,span,level,runavg)
        bargraph.write_to(text_output, format="text")
    else:
        # Create a response object
        response = HttpResponse(content_type='image/png')
        # Generate grapher
        bargraph = PrecipBarGraph(lat,lon,month,span,level,runavg)
        # Write graph to response
        bargraph.write_to(response)

    return response

